#!/bin/bash
# image_type "iso/docker/raspi/stratovirt/virtual_machine/embedded/iso_normal"
# iso_type "standard/everything/everything_src/everything_debug/edge/desktop"
# product "openEuler"
# version "22.09"
# release ""
# repo_url "repo url address"
# upload_image_dir "/repositories/release-images/${task_id}/"
set -ex
. $LKP_SRC/lib/chroot_libs.sh

function backup_local_repo()
{
	if [ -d "/etc/yum.repos.d" ];then
		rm -rf /etc/yum.repos.d.bak
		mv /etc/yum.repos.d /etc/yum.repos.d.bak
	fi
}

function restore_local_repo()
{
	if [ -d "/etc/yum.repos.d.bak" ];then
		rm -rf /etc/yum.repos.d
		mv /etc/yum.repos.d.bak /etc/yum.repos.d
	fi
	if [ "${image_type}" != "embedded" ];then
		chroot_clean
	fi
}

function config_ebs_repo()
{
	export yum_conf="/tmp/ebs-repo.conf"
	rm -rf ${yum_conf} && touch ${yum_conf}

	i=1
	for repo in ${repo_url[@]}
	do
		cat >> ${yum_conf} <<-EOF
		[image_ebs_$i]
		name=image_ebs_$i
		baseurl=${repo}
		enabled=1
		gpgcheck=0

		EOF
		let i=i+1
	done
}

trap restore_local_repo EXIT

function make_ebs_iso()
{
	ARCH="$(uname -m)"
	if [ "${ARCH}" != "aarch64" ] && [ "${ARCH}" != "x86_64" ];then
		echo "[ERROR] unsupported architectures: ${ARCH}"
		exit 1
	fi
	if [ ! -n "${image_type}" ];then
		echo "[ERROR] image_type is null"
		exit 1
	fi
	if [ "${image_type}" == "iso" ];then
		if [ ! -n "${iso_type}" ];then
			echo "[ERROR] iso_type is null"
			exit 1
		fi
	fi
	if [ "${image_type}" == "embedded" ];then
		if [ ! -n "${branch}" ];then
			echo "[ERROR] branch is null"
			exit 1
		fi
	else
		if [ ! -n "${product}" ] || [ ! -n "${version}" ] || [ ! -n "${repo_url}" ];then
			echo "[ERROR] please check the params"
			exit 1
		else
			yum install -y util-linux lsof
			backup_local_repo
			config_ebs_repo
		fi

	fi
	if [ "${image_type}" == "embedded" ];then
		bash $LKP_SRC/tests/make_embedded_image.sh || exit 1
	elif [ "${image_type}" == "iso_normal" ];then
		chroot_run "cd ${LKP_SRC}/tests/; bash make_iso_image.sh"
	else
		chroot_run "cd ${LKP_SRC}/tests/; bash make_${image_type}_image.sh"
	fi
}

make_ebs_iso
